# -*- coding: UTF-8 -*-
# 2023/10/23 12:59
import base64
import os.path
import time
from PySide6.QtCore import QThread, Signal
from configobj import ConfigObj
from askingquestions_log import log_out
from requests_message import send_requests

logger = log_out()
conf_writer = ConfigObj("./config.ini", encoding="utf-8")


class thread_refresh_progressbar(QThread):
    refreshSignal = Signal()

    def __init__(self, refre=0.5):
        super(thread_refresh_progressbar, self).__init__()
        self.refre = refre

    def run(self):
        self.flag = True
        while self.flag:
            self.refreshSignal.emit()

            time.sleep(0.5)

    def stop(self):
        self.requestInterruption()
        self.quit()


class thread_requests_message(QThread):
    answer_singnal = Signal(str)

    def __init__(self, _requests, talk_list, model: str, access_token: str, **kwargs):
        super().__init__()

        self._requests = _requests
        self.model = model
        self.talk_list = talk_list
        self.access_token = access_token
        self.kwargs = kwargs

    def run(self):
        """
        以下拉框模型为准,获取对应模型方法。并在子线程发起请求
        """
        self.flag = True
        if self.flag:
            request_method = getattr(self._requests, self.model, None)
            robot_tetx = request_method(self.talk_list, self.access_token, **self.kwargs)
            self.answer_singnal.emit(robot_tetx)

    def stop(self):
        self.requestInterruption()
        self.quit()


class thread_requests_token(QThread):
    token_singnal = Signal(str)

    def __init__(self, api_key: str = None, secret_key: str = None):
        super().__init__()

        self.API_Key = api_key  # 百度AI服务生成的API_Key
        self.Secret_Key = secret_key  # 百度AI服务生成的Secret Key

    def run(self):
        self.flag = True
        while self.flag:
            access_token = send_requests.get_access_token(self.API_Key, self.Secret_Key)

            self.token_singnal.emit(access_token)
            self.sleep(int(29.5 * 60))
            logger.info(f"tokena刷新冷却准备再次刷新")

    def stop(self):
        self.requestInterruption()
        self.quit()


class thread_get_to_img(QThread):
    img_result_signal = Signal(list)

    def __init__(self, body: dict, access_token: str, **kwargs):
        super().__init__()

        self.body = body  # 请求体
        self.access_token = access_token  # 百度AI服务生成的Secret Key
        self.save_path = os.getcwd()

    def run(self):
        try:
            img = send_requests.Stable_Diffusion_XL(self.body, self.access_token)
            logger.info(f"请求文生图成功")

            self.decoding_base64_img(img)
            self.img_result_signal.emit(img)
            logger.info(f"请求文生图,保存图像成功")

        except:
            logger.error(f"请求文生图保存过程出错")
            error_img = [b"iVBORw0KGgoAAAANSUhEUgAAAJkAAAA1CAIAAADd4N54AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAEXRFWHRTb2Z0d2FyZQBTbmlwYXN0ZV0Xzt0AAAcnSURBVHic7ZxfTNtGHMcd2yH/QNpL+CMeCGqlTWnoE6SIF0or1q1ap3Vi6iYktFYrEu2oqKi6iSIqpnbTuqKyshWJbrBFilQkpEoro2NRSzNViJZqmyCkL0PAA0raPILzz7GzB7eXwzj2ObVD5vnz5HN+d/ezv75/vzswpNNpTEcT4DvtgI5i6FpqB11L7aBrqR3InXbg/wIbCjMLiyCJV1YSLqcixgBdyzzBLCxSvf0gaTrWYskujyxjgN7HagddS+2ga5kn8MpKlYwzuXLIo5MDKJOX3IwBupbaQddSO+haagddS+0gI1aQmp1j/llmn0e4JF5qJ3bvIhvqX90JetoHro2HmtH9SW9scNfE3hq8ohylImZ5JR2NgjtkzR7EvCq5pCDSWrKhcMJ7i77vZyOR7b/idrvxQKOp9UNxvzeOtzOBIEi+Nv+Qu4hdHUxOTqWpzMu1QXLGrg4mxicyP126yP2UmLidGPXA/piOtVjOdWWrPTFxm57xpx4/EfhpfALDMMJRVXTksKmtVeQRlHUJL7VL1iXXWEJLetoX+/aGoIocbCSSGJ+g7/utvZ/JbaPU+Qv0jF9WFgzDEh5vbGgY0Tg1Oxe7OQp/RoIwq2uxoeHknSnL2c4cehpZLnHgZaWKG4uNlwmPl+rtFxESwEYiVE9fanYO1TsMi37xZS5CTtxGf2sJj5fq6ZMUEsCsrlE9fQmPVz2XVCVru9z+reF2e9E7bxO7qrkks7ySnLwLlE5T0eilr4t/HEYZJJhAMHlnCiQJRxVWbGNXVuHOVtirUQ/sj6HMnn4WEfzaBNsK6a4lqh1kzR4umVpcSj2aZ1bXgEGaisaGhvGyUvRhG90ltRHWkgkE46M/w3fMx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mqrFdsKLzxQWtsaDg+5tk43i5+EkWWMUB4TWI+eYJZXIIfLz7mSU7eNR5o5EU4tx+zKARMLUeZ4FM4AJl6/GTjozbSXUe6nCDwxj57Tj+a553PIxxV1t7PFXcpdm0IfkuxoWFj88FsAUJZxgBhLfGKcsvZTqqnD+52uCN38InCQsba15PepODjYWkqSs/4xQ+MEY4q2/UBNc61bo/Ui+xAyDIGZI3hkQ31xd8Nyg01Fb31Jrq92tiuXLZ0dsBjpzhFRw6rJCSGYfBu2os72aOssowBYnEfwuUsGRtJeLzJO1MivajBZiXddUUH9xfgxM/U1mpsPihyVpvD2NSotv+Ws53syip4jZbODpF2IssYYED8v1tMIJj68y/wBwgceKld1vHDnSU1O5f6e4E3OyNr9uTNfzYUpn332OcRY0O95AaOLGMOVC11Ch99z0s76FpqB11L7aBrqR10LbWDrqV20LXUDrqW2kHXUjv8C6EUSTje8zt/AAAAAElFTkSuQmCC"]
            self.decoding_base64_img(error_img)
            self.img_result_signal.emit(error_img)

    def decoding_base64_img(self, img_list):
        """
        解码base64图像并保存
        :param img_list:
        :return:
        """
        try:
            count_img = len(img_list)
            for i in range(count_img):
                img_data = base64.b64decode(img_list[i])
                file_name = f"{self.save_path}/{time.time()}.png"
                with open(file_name, 'wb') as f:
                    f.write(img_data)
                    logger.info(f"第{i + 1}张图像{file_name} 保存成功,总共{count_img}张")
        except:
            logger.error(f"保存图像发生错误！！")

    def stop(self):
        self.requestInterruption()
        self.quit()
